package com.dwin.h5.app.ui;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import com.dwin.h5.app.H5Application;
import com.dwin.h5.app.R;
import com.dwin.h5.app.h5.X5WebView;
import com.dwin.h5.app.models.ResponseBean;
import com.dwin.h5.app.models.UserBean;
import com.dwin.h5.app.utils.ActivityUtils;
import com.dwin.h5.app.utils.Constants;
import com.dwin.h5.app.utils.DisplayUtil;
import com.dwin.h5.app.utils.LocalManageUtil;
import com.dwin.h5.app.utils.ToastUtil;
import com.dwin.h5.app.utils.http.OkHttpUtils;
import com.dwin.h5.app.views.dialogs.NetLoadingDialog;
import com.example.qrcode.Constant;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.tencent.smtt.sdk.ValueCallback;

import org.apache.commons.lang3.StringEscapeUtils;
import org.json.JSONObject;
import org.litepal.LitePal;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

//import cn.jpush.android.api.JPushInterface;
import okhttp3.Call;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * H5Activity 基类，处理h5交互指令的刷新操作
 */
public class BaseH5Activity extends AppCompatActivity {
    private static final String TAG = "BaseH5";

    public static final String ACTION_HTTP = "httpCallback";
    public static final String ACTION_MQTT = "mqttCallback";

    private static final int CODE_QRCODE = 999;

    protected SharedPreferences logMessage = null; //用户日志保存
    protected Context mContext;
    protected UserBean mUser;
    protected X5WebView mWebView;
    protected String auth = "";
    protected String language = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.d("BaseActivity", getClass().getSimpleName());
        mContext = this;
        logMessage = getSharedPreferences("logmessage", MODE_PRIVATE);
        List<UserBean> list = LitePal.findAll(UserBean.class);
        if (list != null && list.size() > 0) {
            mUser = list.get(0); // 获取用户信息
            auth = mUser.auth;
        }
//        initViews();
    }

    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(LocalManageUtil.setLocal(newBase));
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (newConfig.fontScale != 1) {
            //非默认值
            getResources();
        }
        super.onConfigurationChanged(newConfig);
    }

    @Override
    public Resources getResources() {
        Resources res = super.getResources();
        if (res.getConfiguration().fontScale != 1) { //非默认值
            Configuration newConfig = new Configuration();
            newConfig.setToDefaults(); //设置默认
            res.updateConfiguration(newConfig, res.getDisplayMetrics());
        }
        return res;
    }

    protected <T extends View> T findView(int id) {
        return (T) findViewById(id);
    }

    protected void showKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    protected void hideKeyboard(View view) {
        InputMethodManager imm = (InputMethodManager) view.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    public boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    // 判断WiFi是否连接
    protected boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo mWifiInfo = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifiInfo.isConnected();
    }

    // 获取当前手机连接wifi网络的mac地址
    protected String getWifiMac() {
        WifiManager wifimanager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
        WifiInfo wifiinfo = wifimanager.getConnectionInfo();
        return wifiinfo.getBSSID();
    }

    /**
     * 权限检查方法
     *
     * @param permissions 权限数组
     * @return
     */
    public boolean hasPermission(String... permissions) {
        for (String permission : permissions) {
            if (ContextCompat.checkSelfPermission(this, permission) != PackageManager.PERMISSION_GRANTED) {
                return false;
            }
        }
        return true;
    }

    /**
     * 提供权限请求方法
     *
     * @param code
     * @param permissions
     */
    public void requestPermissions(int code, String... permissions) {
        ActivityCompat.requestPermissions(this, permissions, code);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case Constants.WRITE_EXTERNAL_CODE:
                doSDCardPermission();
                break;
            case Constants.PHONE_CODE:
                doCallPhone();
                break;
            case Constants.WIFI_PERMISSION_CODE:
                doScanWifis();
                break;
            case Constants.COARSE_LOCATION_CODE:
                List<String> deniedList = new ArrayList<>(); // 遍历所有申请的权限，把被拒绝的权限放入集合
                for (int i = 0; i < grantResults.length; i++) {
                    int grantResult = grantResults[i];
                    if (grantResult == PackageManager.PERMISSION_GRANTED) {
//                       用户同意权限
                    } else {
                        deniedList.add(permissions[i]);
                    }
                }
                if (deniedList.isEmpty()) {
                    doCoarseLocation();
                } else {
                    ToastUtil.toastShort(mContext, R.string.go_setting_open_location_permission);
                }
                break;
            case Constants.CAMERA_CODE:
                doCameraPermission();
                break;
            case Constants.RECORD_AUDIO:
                doRecordAudioPermission();
                break;
        }
    }

    // 父类提供默认的权限处理方法
    public void doSDCardPermission() {
    }

    // 获得拍照，存储空间的访问权限
    public void doCameraPermission() {
    }

    public void doCallPhone() {
    }

    public void doScanWifis() {
    }

    public void doCoarseLocation() {
    }

    public void doRecordAudioPermission() {
    }

    public static final int TIME_SCAN = 100; // 每间隔0.1s轮询查消息
    Handler handler = new Handler();
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            handler.postDelayed(this, TIME_SCAN);
            // 处理h5返回给app的消息队列数据
            if (H5Application.h5MessageTool.getReceiveMsgCount() > 0) {
                String msg = H5Application.h5MessageTool.getReceiveMsg();
                Log.d(TAG, msg);
                try {
                    JSONObject jsonObject = new JSONObject(msg);
                    String type = jsonObject.getString("type");
                    String command = jsonObject.getString("command");
                    String idflag = jsonObject.getString("idflag");

                    if ("4".equals(type)) { // 网络类（http,https,mqtt）
                        JSONObject jsonData = jsonObject.getJSONObject("data");
                        String url = jsonData.getString("url");
                        String method = jsonData.getString("method");
                        JSONObject headers = jsonData.getJSONObject("param");
                        Iterator<String> headerkeys = headers.keys();
                        if ("get".equalsIgnoreCase(method)) {
                            Map<String, String> map = new HashMap<>();
                            while (headerkeys.hasNext()) {
                                String key = headerkeys.next();
                                map.put(key, headers.getString(key));
                            }
                            getHttp(url, idflag, map); // http get 请求
                        } else if ("post".equalsIgnoreCase(method)) {
                            RequestBody body = RequestBody.create(okhttp3.MediaType.parse("application/json; charset=utf-8"), jsonData.getString("param"));
                            postHttp(url, idflag, body);
                        }
                    } else if ("3".equals(type)) { // 音频类
                    } else if ("2".equals(type)) { // 硬件类
                        if ("setSaveData".equals(command)) { // 保存h5的数据
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            Iterator<String> it = jsonData.keys();
                            while (it.hasNext()) {
                                String key = it.next();
                                String value = jsonData.getString(key);
                                // Log.d(TAG, "save data key: " + key + ", value:" + value);
                                logMessage.edit().putString(key, value).commit();

                                // TODO language重新设定，重新启动app
                                if("language".equals(key) && !TextUtils.isEmpty(value)){
                                    reStart(mContext);
                                }
                            }
                        } else if ("getSaveData".equals(command)) { // 读取保存的数据，返回给h5
                            JSONObject jsonData = jsonObject.getJSONObject("data");
                            Iterator<String> it = jsonData.keys();
                            ResponseBean responseBean = new ResponseBean();
                            responseBean.code = 0;
                            responseBean.message = "获取保存数据成功";
                            Map map = new HashMap();
                            while (it.hasNext()) {
                                String key = it.next();
                                String value = logMessage.getString(key, ""); // get log data
                                map.put(key, StringEscapeUtils.escapeJson(value));
                            }
                            // 发送返回的数据给h5
                            responseBean.data = map;
                            appCallH5(mWebView, "", ACTION_HTTP, idflag, responseBean);
                        } else if ("language".equals(command)) {
                            // 获取系统语言
                            String language = LocalManageUtil.getSystemLocaleLng(mContext);
                            String value = logMessage.getString("language", ""); // 保存的语言
                            if (!TextUtils.isEmpty(value) && !value.equals(language)) {
                                // logMessage.edit().putString("language", value).apply(); // 本地保存，与系统不一致，使用本地保存
                                language = value;
                            } else { // 本地保存，和系统相同，或本地为空，使用系统的语言
                                // logMessage.edit().putString("language", language).apply(); // 保存value
                            }
                            ResponseBean responseBean = new ResponseBean();
                            responseBean.code = 0;
                            responseBean.message = "获取手机系统语言成功：" + value.equals(language);
                            Map map = new HashMap();
                            map.put("language", language);
                            responseBean.data = map;
                            appCallH5(mWebView, "", ACTION_HTTP, idflag, responseBean);
                        }
                    } else if ("1".equals(type)) { // 窗口类

                    } else { // 默认值0或为空

                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    // h5语言切换，系统重启
    public static void reStart(Context context) {
        Intent intent = new Intent(context, LoadingActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
    }

    // 是否需要添加uid
    private boolean isNeedAddUniqueId(String url) {
        boolean flag = false;
        if (url.contains("login/vcode") || url.contains("login/password")) {
            flag = true;
        }
        return flag;
    }

    @Override
    protected void onResume() {
        super.onResume();
        handler.postDelayed(runnable, TIME_SCAN);//每两秒执行一次runnable.
    }

    @Override
    protected void onPause() {
        super.onPause();
        handler.removeCallbacks(runnable);
    }


    // HTTP Post 请求
    protected void postHttp(final String url, final String idFlag, RequestBody body) {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        NetLoadingDialog.showprogress(mContext, false);
        language = logMessage.getString("language", "zh");
//        String pushId = JPushInterface.getRegistrationID(getApplicationContext());
        String pushId = "";
        Log.d(TAG, "PUSHID: " + pushId); // 登录相关操作，带上极光推送的pushId
        OkHttpUtils.getInstance().postV2(auth, language, url, pushId, body, new OkHttpUtils.RealCallback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String responseData = response.body().string();
                    Type type = new TypeToken<ResponseBean>() {
                    }.getType();
                    ResponseBean bean = new Gson().fromJson(responseData, type);
                    String msg = bean.message;

                    Log.d(TAG, "postHttp result: " + responseData);
                    JSONObject jsonObject = new JSONObject(responseData);
                    int code = bean.code;
                    if (response.isSuccessful() && code == Constants.HTTP_OK) {
                        if (url.contains("members/login") || url.contains("members/register")) {

                            if (Constants.FLAG_IS_SYSTEM_WEB) {
                                // 使用系统默认的WebView
                                ActivityUtils.switchActivityFinish(BaseH5Activity.this, MainActivityV2.class);
                            } else {
                                // 使用腾讯x5内核的webView
                                ActivityUtils.switchActivityFinish(BaseH5Activity.this, MainActivity.class);
                            }
                            UserBean userBean = new UserBean(); // 处理用户数据存储逻辑
                            JSONObject data = jsonObject.getJSONObject("data");
                            userBean.auth = data.getString("auth");
                            LitePal.deleteAll(UserBean.class); // 先删除所有数据
                            userBean.save(); // 保存数据
                            findAllData();
                            appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
                        } else {
                            appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
                        }
                    } else {
                        appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                NetLoadingDialog.dismissprogress();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                NetLoadingDialog.dismissprogress();
            }
        });
    }


    // get请求
    protected void getHttp(String url, final String idFlag, Map<String, String> map) {
        if (!isNetworkConnected(mContext)) {
            ToastUtil.toastShort(mContext, R.string.net_error);
            return;
        }
        NetLoadingDialog.showprogress(mContext, false);
        language = logMessage.getString("language", "zh");

        OkHttpUtils.getInstance().get(auth, language, url, map, new OkHttpUtils.RealCallback() {
            @Override
            public void onResponse(Call call, Response response) {
                try {
                    String responseData = response.body().string();
                    Log.d(TAG, "getHttp result: " + responseData);
                    Type type = new TypeToken<ResponseBean>() {
                    }.getType();
                    ResponseBean bean = new Gson().fromJson(responseData, type);
                    String msg = bean.message;
                    appCallH5(mWebView, "", ACTION_HTTP, idFlag, bean);
                    if (response.isSuccessful() && bean.code == Constants.HTTP_OK) {

                    } else {
//                        ToastUtil.toastShort(mContext, msg);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                NetLoadingDialog.dismissprogress();
            }

            @Override
            public void onFailure(Call call, IOException e) {
                NetLoadingDialog.dismissprogress();
            }
        });
    }

    /**
     * app 调用h5的方法
     *
     * @param webView
     * @param method
     * @param action
     * @param idFlag
     * @param data
     */
    @Deprecated
    protected void appCallH5(final X5WebView webView, String method, String action, String idFlag, String data) {
        this.mWebView = webView;
        final Map<String, String> map = new HashMap<>();
        map.put("idflag", idFlag);
        map.put("data", data);
        final String json = new Gson().toJson(map);
        Log.d(TAG, "appCallH5 json--> " + json);
//        H5Application.h5MessageTool.addSendMsg(jsonObject.toString()); // TODO 发送消息到发送队列中
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript("javascript:appCallH5('" + json + "')", new ValueCallback<String>() { // TODO ok
                    //   webView.evaluateJavascript("javascript:appCallH5('999')", new ValueCallback<String>() { // TODO ok
                    @Override
                    public void onReceiveValue(String s) {
                        Log.d(TAG, "onReceiveValue" + s);
                    }
                });
            }
        });
    }

    protected void appCallH5(final X5WebView webView, String method, String action, String idFlag, Object object) {
        this.mWebView = webView;
        final Map<String, Object> map = new HashMap<>();
        map.put("idflag", idFlag);
        map.put("data", object);
        final String json = new Gson().toJson(map);
        Log.d(TAG, "appCallH5 json--> " + json);
//        H5Application.h5MessageTool.addSendMsg(jsonObject.toString()); //  发送消息到发送队列中
        mWebView.post(new Runnable() {
            @Override
            public void run() {
                webView.evaluateJavascript("javascript:appCallH5('" + json + "')", new ValueCallback<String>() { // TODO ok
                    //   webView.evaluateJavascript("javascript:appCallH5('999')", new ValueCallback<String>() { //  ok
                    @Override
                    public void onReceiveValue(String s) {
                        Log.d(TAG, "onReceiveValue" + s);
                    }
                });
            }
        });
    }

    private void actionScanCode() {
        Intent intent = new Intent(mContext, com.example.qrcode.ScannerActivity.class);
        // 设置扫码框的宽
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_WIDTH, DisplayUtil.dip2px(mContext, 257));
        // 设置扫码框的高
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_HEIGHT, DisplayUtil.dip2px(mContext, 257));
        // 设置扫码框距顶部的位置
        intent.putExtra(Constant.EXTRA_SCANNER_FRAME_TOP_PADDING, DisplayUtil.dip2px(mContext, 136));
        // 可以从相册获取
        intent.putExtra(Constant.EXTRA_IS_ENABLE_SCAN_FROM_PIC, true);
        startActivityForResult(intent, CODE_QRCODE);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CODE_QRCODE && resultCode == Activity.RESULT_OK) { // 二维码扫描结果
            if (data == null) {
                return;
            }
            String result = data.getExtras().getString(Constant.EXTRA_RESULT_CONTENT);
        }
    }


    private void findAllData() {
        List<UserBean> list = LitePal.findAll(UserBean.class);
        Log.d(TAG, "查询结果--------start------： ");
        for (UserBean userBean : list) {
            Log.d(TAG, "查询结果： " + userBean.toString());
        }
        Log.d(TAG, "查询结果------/--end------： ");
    }

}
